package io.xccit.hotelsystem.ui.order;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import io.xccit.hotelsystem.databinding.FragmentOrderBinding;
import io.xccit.hotelsystem.ui.login.LoginActivity;
import io.xccit.hotelsystem.ui.order.adapter.OrderAdapter;
import io.xccit.hotelsystem.utils.AuthUtils;

/**
 * 订单Fragment
 */
public class OrderFragment extends Fragment {

    private FragmentOrderBinding binding;
    private OrderViewModel orderViewModel;
    private OrderAdapter orderAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        orderViewModel =
                new ViewModelProvider(this, new ViewModelProvider.Factory() {
                    @NonNull
                    @Override
                    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                        return (T) new OrderViewModel(requireContext());
                    }
                }).get(OrderViewModel.class);

        binding = FragmentOrderBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 检查登录状态
        if (!AuthUtils.checkLoginAndRedirect(requireContext(), LoginActivity.class)) {
            return root;
        }
        
        // 从登录信息获取用户名
        SharedPreferences prefs = requireContext().getSharedPreferences(AuthUtils.PREF_NAME, Context.MODE_PRIVATE);
        String username = prefs.getString(AuthUtils.KEY_USERNAME, null);
        
        // 设置VIP会员信息
        binding.tvVipInfo.setText("尊贵的VIP会员：" + username);
        
        // 设置RecyclerView
        RecyclerView rvOrders = binding.rvOrders;
        rvOrders.setLayoutManager(new LinearLayoutManager(getContext()));
        orderAdapter = new OrderAdapter(getContext(), null, orderId -> {
            // 跳转到订单详情
            Intent intent = new Intent(requireContext(), OrderDetailActivity.class);
            intent.putExtra("order_id", orderId);
            startActivity(intent);
        });
        rvOrders.setAdapter(orderAdapter);
        
        // 加载订单数据
        orderViewModel.loadUserOrders(username);
        orderViewModel.getOrders().observe(getViewLifecycleOwner(), cursor -> {
            orderAdapter.swapCursor(cursor);
        });
        
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        orderAdapter.swapCursor(null);
        binding = null;
    }
}